from flask import Flask, jsonify, render_template
import numpy as np
import threading
import time

app = Flask(__name__)

# 模拟数据采集线程
class DataGenerator:
    def __init__(self):
        self.data_buffer = np.zeros((1000, 16), dtype=np.uint16)
        self.lock = threading.Lock()
        self.running = True
        
    def generate_data(self):
        """模拟数据采集线程，每秒更新一次数据"""
        while self.running:
            # 生成随机数据模拟真实采集
            new_data = np.random.randint(0, 65535, (1000, 16), dtype=np.uint16)
            with self.lock:
                self.data_buffer = new_data
            time.sleep(1)  # 模拟1秒采集周期
    
    def get_latest_data(self):
        """获取最新数据切片"""
        with self.lock:
            return self.data_buffer.copy()

# 初始化数据生成器
data_gen = DataGenerator()
thread = threading.Thread(target=data_gen.generate_data)
thread.daemon = True
thread.start()

@app.route('/')
def index():
    """主页面服务"""
    return render_template('index.html')

@app.route('/data')
def get_data():
    """提供最新数据API"""
    data = data_gen.get_latest_data()
    # 转换为前端需要的格式
    channels = {}
    for i in range(16):
        channels[f'ch{i}'] = data[:, i].tolist()
    return jsonify(channels)

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, threaded=True)